import { subscribeWithSelector } from 'zustand/middleware'
import create from 'zustand'
import { Vmp } from './interface'
import Alert from '@/components/Alert'
import { t } from 'i18next'
import { UserEntity } from '@/api/create/interface'
import { RevertPlanEntity } from './VmpPlan/interface'

type StateStore = {
	/**画面合成开关 */
	enable: boolean
	/**定制画面合成开关*/
	enable_custom?: boolean
	_meetingType: number
	state: 0 | 1
	/**VmpPoll用到的元素*/
	pollPlanOptions: Array<{ label: string; value: string }>
	pollPlanValue: string
	pollIntervalOptionsVal: number
	pollInterval: string
	pollTimes: string
	unlimited: boolean
	pollPlanName: string
	pollMembers: Array<UserEntity>
	// VmpPlan
	vmpPlanName: string
	vmpPlanValue: string
	planOptions: Array<RevertPlanEntity>
	needUpdate: any
} & Vmp

type IStore = StateStore & {
	update: (d: Partial<StateStore>) => void
	reset: () => void
	/**设置批量轮询的数据*/
	setBatchPollParams: (d: Partial<Vmp['poll']>) => void
	checkVmpPollData: () => boolean
}

const initialState: StateStore = {
	id: '',
	voice_hint: 0,
	members: [],
	state: 0,
	enable: false,
	name: '',
	mode: 2,
	show_mt_name: 1,
	broadcast: 0,
	except_self: 0,
	mt_name_style: {
		font_color: '#FFFFFF',
		font_size: 1,
		position: 1,
	},
	layout: 0,
	poll: {
		id: '',
		keep_time: 30,
		members: [],
		mode: 1,
		name: '',
		num: 0,
	},
	_meetingType: 1,
	pollPlanOptions: [{ label: t('不使用预案'), value: '0' }],
	pollPlanValue: '0',
	pollIntervalOptionsVal: 30,
	pollInterval: '5',
	pollTimes: '',
	unlimited: true,
	pollPlanName: '',
	pollMembers: [],
	vmpPlanName: '',
	vmpPlanValue: '0',
	planOptions: [{ label: t('默认预案'), value: '0', mode: undefined, layout: undefined }],
	needUpdate: {},
}

export const useMeetingVmpStore = create<IStore>()(
	subscribeWithSelector((set, get) => ({
		...initialState,
		update: (d) => set({ ...d }),
		reset: () => set(initialState),
		setBatchPollParams: (d) => {
			set({ pollMembers: d?.members })
		},
		checkVmpPollData: () => {
			const { mode, unlimited, pollInterval, pollTimes, pollIntervalOptionsVal, pollMembers } = get()
			if (mode === 4) {
				if (pollIntervalOptionsVal === 0) {
					if (pollInterval === '') {
						Alert(t('请设置轮询间隔'))
						return false
					} else if (Number(pollInterval) < 5 || Number(pollInterval) > 7200) {
						Alert(t('轮询间隔应为5~7200秒'))
						return false
					}
				}
				if (!unlimited) {
					if (pollTimes === '') {
						Alert(t('请设置轮询次数'))
						return false
					} else if (Number(pollTimes) < 1 || Number(pollTimes) > 9999) {
						Alert(t('轮询次数应为1~9999次'))
						return false
					}
				}
				if (pollMembers.length === 0) {
					Alert(t('批量轮询列表不能为空'))
					return false
				}
				return true
			}
			return true
		},
	}))
)
